package evo.selectors;

import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

import evo.IInstance;

public class TournamentSelector implements ISelector {

	private Random _r = new Random();
	
	@Override
	public ArrayList<IInstance> select(Map<IInstance, Double> pool, int n) {
		ArrayList<IInstance> selection = new ArrayList<IInstance>(n);
		while (selection.size() < n)
		{
			Entry<IInstance, Double> a = randomInstance(pool);
			Entry<IInstance, Double> b = randomInstance(pool);
			if (a.getValue() > b.getValue())
				selection.add(a.getKey());
			else
				selection.add(b.getKey());
		}
		return selection;
	}
	
	
	@SuppressWarnings("unchecked")
	private Entry<IInstance, Double> randomInstance(Map<IInstance, Double> collection)
	{
		int r = this._r.nextInt(collection.size());
		return (Entry<IInstance, Double>)collection.entrySet().toArray()[r];
	}

}
